package com.marco.system.service.impl;

import com.google.common.collect.Maps;
import com.marco.system.dao.ChinaAdInfoDao;
import com.marco.system.domain.ChinaAdInfo;
import com.marco.system.service.ChinaAdInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

/**
 * ChinaAdInfoServiceImpl.java
 * Create on 2017/3/23
 * Copyright(c) JD Inc 2017. All Rights Reserved.
 * <pre>
 * 功能说明：
 * </pre>
 */
@Service
@Transactional
public class ChinaAdInfoServiceImpl implements ChinaAdInfoService {
    private static final Logger logger = LoggerFactory.getLogger(ChinaAdInfoServiceImpl.class);
    private static Map<String, List<ChinaAdInfo>> chinaAdMaps;

    @Autowired
    private ChinaAdInfoDao chinaAdInfoDao;

    @PostConstruct
    private void initChinaAdMaps() {
        chinaAdMaps = Maps.newHashMap();
        try {
            logger.info("正在构建中国行政区与京东ID映射字典，请稍候、、、、、");
            String parentKey = "0";
            List<ChinaAdInfo> provinceList = chinaAdInfoDao.findByParentCode(parentKey);
            chinaAdMaps.put(parentKey, provinceList);
            for (ChinaAdInfo province : provinceList) {
                parentKey = province.getCode();
                List<ChinaAdInfo> cityList = chinaAdInfoDao.findByParentCode(parentKey);
                chinaAdMaps.put(parentKey, cityList);
                for (ChinaAdInfo city : cityList) {
                    parentKey = city.getCode();
                    List<ChinaAdInfo> countyList = chinaAdInfoDao.findByParentCode(parentKey);
                    chinaAdMaps.put(parentKey, countyList);
                }
            }
            logger.info("构建中国行政区与京东ID映射字典完成!");
        } catch (Exception e) {
            throw new RuntimeException(" 获取中国标准地址字典异常 ！", e);
        }
    }

    @Override
    public Map<String, List<ChinaAdInfo>> getJdChinaMap() {
        return chinaAdMaps;
    }

    @Override
    public ChinaAdInfo getAdInfoByNameAndId(String id, String name) {
        try {
            return chinaAdInfoDao.findAdByNameAndId(id,name);
        } catch (Exception e) {
            logger.error("查询出现异常", e);
        }
        return null;
    }
}
